package cn.wizzer.app.web.modules.controllers.platform.bus;

import cn.wizzer.app.bus.modules.models.BusinessFileInfo;
import cn.wizzer.app.bus.modules.services.BusinessFileInfoService;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.PageUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

@IocBean
@At("/platform/bus/certification")
public class CertificationController {

    private static final Log log = Logs.get();

    @Inject
    private BusinessFileInfoService businessFileInfoService;
    @Inject
    private SysDictService sysDictService;

    @At("")
    @Ok("beetl:/platform/bus/configManagement/certification/index.html")
    @RequiresPermissions("bus.config_management.certification")
    public void index(HttpServletRequest req) {

    }

    @At
    @Ok("json:full")
    @RequiresPermissions("bus.config_management.certification.data")
    public Object data(
            @Param("pageNumber") int pageNumber,
            @Param("pageSize") int pageSize,
            @Param("pageOrderName") String pageOrderName,
            @Param("pageOrderBy") String pageOrderBy,
            @Param("reportTemplateName") String reportTemplateName
    ) {
        try {
            String sql ="select * from  bus_file_info where delFlag=0 and infoType = 'certification' ";

            if(StringUtils.isNotBlank(reportTemplateName)){
                sql+=" infoName like '%"+reportTemplateName+"%' ";
            }
            sql+=StringUtil.dataScopeFilter("");
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                if ("ascending".equalsIgnoreCase(pageOrderBy)) {
                    sql+= " order by "+pageOrderName+" asc,opAt desc ";
                } else {
                    sql+= " order by "+pageOrderName+" desc,opAt desc ";
                }
            }else{
                sql+= " order by opAt desc ";
            }

            return Result.success().addData(businessFileInfoService.listPage(pageNumber, pageSize, Sqls.create(sql)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At
    @Ok("json")
    @RequiresPermissions("bus.config_management.certification.add")
    @SLog(tag = "添加认证方式", msg = "认证方式:${businessFileInfo.infoName}")
    public Object addDo(@Param("..") BusinessFileInfo businessFileInfo, HttpServletRequest req) {
        try {
            businessFileInfo.setInfoName(Strings.trim(businessFileInfo.getInfoName()));
            businessFileInfo.setInfoVersion(Strings.trim(businessFileInfo.getInfoVersion()));
            businessFileInfo.setInfoType("certification");
            businessFileInfo.setRemark(Strings.trim(businessFileInfo.getRemark()));
            businessFileInfo.setOpBy(StringUtil.getPlatformUid());
            businessFileInfo.setOperatorName(StringUtil.getPlatformUsername());
            businessFileInfo.setDisabled(false);
            businessFileInfoService.insert(businessFileInfo);
            businessFileInfoService.deleteCache(businessFileInfo.getId());
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }
    @At
    @Ok("json")
    @RequiresPermissions("bus.config_management.certification.edit")
    @SLog(tag = "修改认证方式", msg = "认证方式:${businessFileInfo.infoName}")
    public Object editDo(@Param("..") BusinessFileInfo businessFileInfo, HttpServletRequest req) {
        try {
            businessFileInfo.setOperatorName(StringUtil.getPlatformUsername());
            businessFileInfo.setDisabled(false);
            businessFileInfoService.update(businessFileInfo);
            businessFileInfoService.deleteCache(businessFileInfo.getId());
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }
    @At("/detail/?")
    @Ok("json")
    public Object detail(String reportTemplateId, HttpServletRequest req) {
        try {
            BusinessFileInfo businessFileInfo = businessFileInfoService.fetch(reportTemplateId);
            return Result.success(businessFileInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }


    @At("/enable/?")
    @Ok("json")
    @RequiresPermissions("bus.config_management.certification.edit")
    @SLog(tag = "启用认证方式", msg = "认证方式ID:${args[1].getAttribute('templateId')}")
    public Object enable(String reportTemplateId, HttpServletRequest req) {
        try {
            req.setAttribute("templateId", reportTemplateId);
            businessFileInfoService.update(Chain.make("disabled", false), Cnd.where("id", "=", reportTemplateId));
            businessFileInfoService.deleteCache(reportTemplateId);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/disable/?")
    @Ok("json")
    @RequiresPermissions("bus.config_management.certification.edit")
    @SLog(tag = "禁用认证方式", msg = "认证方式ID:${args[1].getAttribute('templateId')}")
    public Object disable(String reportTemplateId, HttpServletRequest req) {
        try {
            req.setAttribute("templateId", reportTemplateId);
            businessFileInfoService.update(Chain.make("disabled", true), Cnd.where("id", "=", reportTemplateId));
            businessFileInfoService.deleteCache(reportTemplateId);
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @At("/delete/?")
    @Ok("json")
    @RequiresPermissions("bus.config_management.certification.delete")
    @SLog(tag = "删除认证方式", msg = "认证方式ID:${args[1].getAttribute('templateId')}")
    public Object delete(String reportTemplateId, HttpServletRequest req) {
        try {
            //逻辑删除
            req.setAttribute("templateId", reportTemplateId);
            businessFileInfoService.vDelete(reportTemplateId);
            businessFileInfoService.clearCache();
            return Result.success();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }
}
